package com.yuelao.yuelao_backend.controller;

import com.yuelao.yuelao_backend.common.ApiResponse;
import com.yuelao.yuelao_backend.common.BizException;
import com.yuelao.yuelao_backend.common.ErrorCode;
import com.yuelao.yuelao_backend.dto.MessageDTO;
import com.yuelao.yuelao_backend.dto.request.SendMessageRequest;
import com.yuelao.yuelao_backend.entity.Conversation;
import com.yuelao.yuelao_backend.service.ConversationService;
import com.yuelao.yuelao_backend.service.FileUploadService;
import com.yuelao.yuelao_backend.service.GroupMessageService;
import com.yuelao.yuelao_backend.service.MessageService;
import com.yuelao.yuelao_backend.util.UserContextUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 消息Controller
 * 重构说明：适配新的MessageService、GroupMessageService和ConversationService
 */
@RestController
@RequestMapping
@Slf4j
@RequiredArgsConstructor
public class MessageController {

    private final MessageService messageService;
    private final GroupMessageService groupMessageService;
    private final ConversationService conversationService;
    private final FileUploadService fileUploadService;

    /**
     * 获取会话列表
     * GET /conversations
     * @return 会话列表
     */
    @GetMapping("/messages/list")
    public ApiResponse<List<Conversation>> getUserConversations() {
        Long userId = UserContextUtil.getCurrentUserId();
        List<Conversation> conversations = conversationService.getUserConversations(userId);
        return ApiResponse.ok(conversations);
    }

    /**
     * 获取私聊记录
     * GET /messages/{targetUserId}
     * @param targetUserId 聊天对象ID
     * @param page 页码，默认1
     * @param size 每页数量，默认10
     * @return 私聊记录列表
     */
    @GetMapping("/messages/{targetUserId}")
    public ApiResponse<List<MessageDTO>> getChatHistory(
            @PathVariable Long targetUserId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Long userId = UserContextUtil.getCurrentUserId();
        if (targetUserId == null || targetUserId <= 0) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "聊天对象ID无效");
        }
        List<MessageDTO> chatHistory = messageService.getChatHistory(userId, targetUserId, page, size);
        return ApiResponse.ok(chatHistory);
    }

    /**
     * 发送私聊消息
     * POST /messages/send
     * @param request 消息请求
     * @return 是否成功
     */
    @PostMapping("/messages/send")
    public ApiResponse<Boolean> sendMessage(@Valid @RequestBody SendMessageRequest request) {
        Long userId = UserContextUtil.getCurrentUserId();
        boolean result = messageService.sendMessage(
            userId,
            request.getReceiverId(),
            request.getMessageType(),
            request.getContent(),
            request.getMediaUrl()
        );
        return ApiResponse.ok(result);
    }

    /**
     * 标记消息为已读
     * PUT /messages/{messageId}/read
     * @param messageId 消息ID
     * @return 是否成功
     */
    @PutMapping("/messages/{messageId}/read")
    public ApiResponse<Boolean> markAsRead(@PathVariable Long messageId) {
        boolean result = messageService.markAsRead(messageId);
        return ApiResponse.ok(result);
    }

    /**
     * 撤回消息
     * DELETE /messages/{messageId}/revoke
     * @param messageId 消息ID
     * @return 是否成功
     */
    @DeleteMapping("/messages/{messageId}/revoke")
    public ApiResponse<Boolean> revokeMessage(@PathVariable Long messageId) {
        Long userId = UserContextUtil.getCurrentUserId();
        boolean result = messageService.revokeMessage(messageId, userId);
        return ApiResponse.ok(result);
    }

    /**
     * 获取群聊记录
     * GET /groups/{groupId}/messages
     * @param groupId 群聊ID
     * @param page 页码，默认1
     * @param size 每页数量，默认10
     * @return 群聊记录列表
     */
    @GetMapping("/groups/{groupId}/messages")
    public ApiResponse<List<MessageDTO>> getGroupChatHistory(
            @PathVariable Long groupId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        if (groupId == null || groupId <= 0) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "群聊ID无效");
        }
        List<MessageDTO> groupChatHistory = groupMessageService.getGroupChatHistory(groupId, page, size);
        return ApiResponse.ok(groupChatHistory);
    }

    /**
     * 发送群聊消息
     * POST /groups/{groupId}/messages/send
     * @param groupId 群聊ID
     * @param request 消息请求
     * @return 是否成功
     */
    @PostMapping("/groups/{groupId}/messages/send")
    public ApiResponse<Boolean> sendGroupMessage(
            @PathVariable Long groupId,
            @Valid @RequestBody SendMessageRequest request) {
        Long userId = UserContextUtil.getCurrentUserId();
        boolean result = groupMessageService.sendGroupMessage(
            userId,
            groupId,
            request.getMessageType(),
            request.getContent(),
            request.getMediaUrl()
        );
        return ApiResponse.ok(result);
    }

    /**
     * 撤回群聊消息
     * DELETE /groups/messages/{messageId}/revoke
     * @param messageId 消息ID
     * @return 是否成功
     */
    @DeleteMapping("/groups/messages/{messageId}/revoke")
    public ApiResponse<Boolean> revokeGroupMessage(@PathVariable Long messageId) {
        Long userId = UserContextUtil.getCurrentUserId();
        boolean result = groupMessageService.revokeGroupMessage(messageId, userId);
        return ApiResponse.ok(result);
    }

    /**
     * 发送图片消息
     * POST /messages/send/image
     * @param receiverId 接收者ID
     * @param file 图片文件
     * @return 是否成功
     */
    @PostMapping("/messages/send/image")
    public ApiResponse<Boolean> sendImageMessage(
            @RequestParam Long receiverId,
            @RequestParam("file") MultipartFile file) {
        Long userId = UserContextUtil.getCurrentUserId();
        
        try {
            // 上传图片
            String mediaUrl = fileUploadService.uploadFile(file, "image");
            
            // 发送消息
            boolean result = messageService.sendMessage(userId, receiverId, "image", null, mediaUrl);
            return ApiResponse.ok(result);
        } catch (Exception e) {
            log.error("发送图片消息失败: {}", e.getMessage(), e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR, "发送图片消息失败: " + e.getMessage());
        }
    }

    /**
     * 发送语音消息
     * POST /messages/send/voice
     * @param receiverId 接收者ID
     * @param file 语音文件
     * @return 是否成功
     */
    @PostMapping("/messages/send/voice")
    public ApiResponse<Boolean> sendVoiceMessage(
            @RequestParam Long receiverId,
            @RequestParam("file") MultipartFile file) {
        Long userId = UserContextUtil.getCurrentUserId();
        
        try {
            // 上传语音
            String mediaUrl = fileUploadService.uploadFile(file, "voice");
            
            // 发送消息
            boolean result = messageService.sendMessage(userId, receiverId, "voice", null, mediaUrl);
            return ApiResponse.ok(result);
        } catch (Exception e) {
            log.error("发送语音消息失败: {}", e.getMessage(), e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR, "发送语音消息失败: " + e.getMessage());
        }
    }

    /**
     * 发送视频消息
     * POST /messages/send/video
     * @param receiverId 接收者ID
     * @param file 视频文件
     * @return 是否成功
     */
    @PostMapping("/messages/send/video")
    public ApiResponse<Boolean> sendVideoMessage(
            @RequestParam Long receiverId,
            @RequestParam("file") MultipartFile file) {
        Long userId = UserContextUtil.getCurrentUserId();
        
        try {
            // 上传视频
            String mediaUrl = fileUploadService.uploadFile(file, "video");
            
            // 发送消息
            boolean result = messageService.sendMessage(userId, receiverId, "video", null, mediaUrl);
            return ApiResponse.ok(result);
        } catch (Exception e) {
            log.error("发送视频消息失败: {}", e.getMessage(), e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR, "发送视频消息失败: " + e.getMessage());
        }
    }

    /**
     * 发送群聊图片消息
     * POST /groups/{groupId}/messages/send/image
     * @param groupId 群聊ID
     * @param file 图片文件
     * @return 是否成功
     */
    @PostMapping("/groups/{groupId}/messages/send/image")
    public ApiResponse<Boolean> sendGroupImageMessage(
            @PathVariable Long groupId,
            @RequestParam("file") MultipartFile file) {
        Long userId = UserContextUtil.getCurrentUserId();
        
        try {
            // 上传图片
            String mediaUrl = fileUploadService.uploadFile(file, "image");
            
            // 发送群聊消息
            boolean result = groupMessageService.sendGroupMessage(userId, groupId, "image", null, mediaUrl);
            return ApiResponse.ok(result);
        } catch (Exception e) {
            log.error("发送群聊图片消息失败: {}", e.getMessage(), e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR, "发送群聊图片消息失败: " + e.getMessage());
        }
    }

    /**
     * 发送群聊语音消息
     * POST /groups/{groupId}/messages/send/voice
     * @param groupId 群聊ID
     * @param file 语音文件
     * @return 是否成功
     */
    @PostMapping("/groups/{groupId}/messages/send/voice")
    public ApiResponse<Boolean> sendGroupVoiceMessage(
            @PathVariable Long groupId,
            @RequestParam("file") MultipartFile file) {
        Long userId = UserContextUtil.getCurrentUserId();
        
        try {
            // 上传语音
            String mediaUrl = fileUploadService.uploadFile(file, "voice");
            
            // 发送群聊消息
            boolean result = groupMessageService.sendGroupMessage(userId, groupId, "voice", null, mediaUrl);
            return ApiResponse.ok(result);
        } catch (Exception e) {
            log.error("发送群聊语音消息失败: {}", e.getMessage(), e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR, "发送群聊语音消息失败: " + e.getMessage());
        }
    }

    /**
     * 发送群聊视频消息
     * POST /groups/{groupId}/messages/send/video
     * @param groupId 群聊ID
     * @param file 视频文件
     * @return 是否成功
     */
    @PostMapping("/groups/{groupId}/messages/send/video")
    public ApiResponse<Boolean> sendGroupVideoMessage(
            @PathVariable Long groupId,
            @RequestParam("file") MultipartFile file) {
        Long userId = UserContextUtil.getCurrentUserId();
        
        try {
            // 上传视频
            String mediaUrl = fileUploadService.uploadFile(file, "video");
            
            // 发送群聊消息
            boolean result = groupMessageService.sendGroupMessage(userId, groupId, "video", null, mediaUrl);
            return ApiResponse.ok(result);
        } catch (Exception e) {
            log.error("发送群聊视频消息失败: {}", e.getMessage(), e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR, "发送群聊视频消息失败: " + e.getMessage());
        }
    }
}
